<template>
    <div>
        <el-button @click="add" type="primary" icon="el-icon-plus" style="margin: 10px 0;"></el-button>
        <el-table :data="records" style="width: 100%" border v-loading="loading">
            <el-table-column type="index" label="序号" align="center" width="80px"></el-table-column>

            <el-table-column prop="tmName" label="品牌名称"></el-table-column>

            <!-- 如果要使用插槽column不需要使用prop指定显示属性,它内部会使用row(当前行数据)进行数据回显 -->
            <el-table-column label="品牌LOGO">
                <template slot-scope="{row,$index}">
                    <img :src="row.logoUrl" alt="" width="120" height="80">
                </template>
            </el-table-column>

            <el-table-column prop="address" label="操作">
                <template slot-scope="{row,$index}">
                    <el-button @click="update(row)" type="warning" icon="el-icon-edit" size="mini">修改</el-button>
                    <el-button type="danger" icon="el-icon-delete" size="mini" @click="del(row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>

        <el-pagination :current-page="page" :page-size="limit" :pager-count="5" style="text-align: center" background
                       @size-change="sizeChange" @current-change="getAllTradeMarkByPage" :page-sizes="[3,5,10]"
                       layout="prev, pager, next,jumper,->,sizes,total" :total="total"></el-pagination>

        <!--<el-dialog :visible="dialogFormVisible" @update:visible="dialogFormVisible=$event"></el-dialog>-->
        <el-dialog :title="form.id?'修改':'添加'" :visible.sync="dialogFormVisible">
            <el-form :model="form" :rules="rules" ref="tmForm">
                <el-form-item label="品牌名称" prop="tmName" :label-width="formLabelWidth">
                    <!--<el-input :value="form.name" @input="form.name=$event"></el-input>                    -->
                    <el-input v-model="form.tmName" autocomplete="on"></el-input>
                </el-form-item>

                <el-form-item label="品牌LOGO" prop="logoUrl" :label-width="formLabelWidth">
                    <el-upload class="avatar-uploader" :action="`${$BASE_API}/admin/product/fileUpload`"
                            :show-file-list="false" :on-success="handleAvatarSuccess" :before-upload="beforeAvatarUpload">

                        <img v-if="form.logoUrl" :src="form.logoUrl" class="avatar">

                        <i v-else class="el-icon-plus avatar-uploader-icon"></i>

                        <div class="el-upload__tip" slot="tip">只能上传jpg文件，且不超过500kb</div>
                    </el-upload>
                </el-form-item>
            </el-form>

            <div slot="footer" class="dialog-footer">
                <el-button @click="dialogFormVisible = false">取 消</el-button>
                <el-button type="primary" @click="save">确 定</el-button>
            </div>
        </el-dialog>
    </div>
</template>

<script>
    export default {
        data() {
            const validateMessage = (rule, value, callback) => {
                if(value==='fuck') {
                    callback(new Error('不要敏感信息'));
                }else {
                    callback();
                }
            };
            return {
                page: 1,
                limit: 3,
                records: [],
                total: 0,
                loading: false,      // 控制table的loading动画
                dialogFormVisible: false,
                formLabelWidth: '180px',
                form: {
                    logoUrl: '',
                    tmName:  '',
                },
                rules: {
                    tmName: [
                        {required: true, message: '图片名称不能为空', trigger: 'change'},
                        { min: 2, max: 8, message: '长度在 2 到 8 个字符', trigger: 'change' },
                        {validator: validateMessage, trigger: 'change'},
                    ],
                    logoUrl: [
                        { required: true, message: '图片LOGO不能为空', trigger: 'blur'},
                    ]
                },
            }
        },

        methods: {
            async getAllTradeMarkByPage(pager = 1) {
                this.page = pager;
                try {
                    this.loading = true;

                    const {code,data} = await this.$API.trademark.getAllTradeMarkByPage(this.page,this.limit);

                    if(code === 200) {
                        this.records = data.records;
                        this.total = data.total;
                        this.loading = false;
                    }
                }catch (e) {
                    this.$message({
                        message: '请求失败',
                        type: 'error',
                    });
                }
            },

            sizeChange(limit) {
                this.limit = limit;
                this.getAllTradeMarkByPage();
            },

            add() {
                this.form = {
                    logoUrl: '',
                    tmName:  '',
                };

                this.dialogFormVisible = true;

                // 清除所有校验信息(当展示dialog组件时,可能tmForm还没被渲染完成)
                this.$nextTick(() => {
                    this.$refs.tmForm.clearValidate();
                });
            },

            handleAvatarSuccess(res, file) {
                this.form.logoUrl = res.data;

                this.$nextTick(() => {
                    this.$refs.tmForm.clearValidate('logoUrl');
                })
            },

            beforeAvatarUpload(file) {
                const isJPG = file.type === 'image/jpeg';
                const isLt2M = file.size / 1024  < 50;

                if (!isJPG) {
                    this.$message.error('上传头像图片只能是 JPG 格式!');
                }
                if (!isLt2M) {
                    this.$message.error('上传头像图片大小不能超过 50KB!');
                }
                return isJPG && isLt2M;
            },

            update(row) {
                this.dialogFormVisible = true;
                this.form = {...row};
            },

            save() {
                const trademark = this.form;
                this.$refs.tmForm.validate(async (valid) => {
                    if(valid) {
                        const {code} = await this.$API.trademark.addAndUpdate(trademark);
                        if(code === 200) {
                            this.dialogFormVisible = false;

                            this.$message({
                                message: `${trademark.id?"修改成功":"添加成功"}`,
                                type: 'success'
                            });

                            const pageNo = trademark.id ? this.page: 1;
                            this.getAllTradeMarkByPage(pageNo);
                        }
                    }else {
                        this.$message({
                            message: '提交失败',
                            type: 'error'
                        });
                    }
                });

            },

            del(row) {
                this.$confirm(`是否删除${row.tmName}`, '删除', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                    center: true
                }).then(async () => {
                    const {code} = await this.$API.trademark.delTradeMarkById(row.id);
                    if(code === 200) {
                        this.$message({
                            type: 'success',
                            message: '删除成功!'
                        });

                        const pageNo =(this.records.length>1 || this.total ===1)?this.page:this.page-1;
                        this.getAllTradeMarkByPage(pageNo);
                    }
                }).catch(() => {
                    this.$message({
                        type: 'info',
                        message: '已取消删除'
                    });
                });
            }
        },

        mounted() {
            this.getAllTradeMarkByPage();
        },

        name: "TradeMark",

    }
</script>

<style>
    .avatar-uploader .el-upload {
        border: 1px dashed #d9d9d9;
        border-radius: 6px;
        cursor: pointer;
        position: relative;
        overflow: hidden;
    }
    .avatar-uploader .el-upload:hover {
        border-color: #409EFF;
    }
    .avatar-uploader-icon {
        font-size: 28px;
        color: #8c939d;
        width: 178px;
        height: 178px;
        line-height: 178px;
        text-align: center;
    }
    .avatar {
        width: 178px;
        height: 178px;
        display: block;
    }
</style>
